import os

from fastapi import APIRouter,HTTPException, Request
from application.utils import func, aliyunclound
from application import settings
from application.utils.log import getLogger

app = APIRouter()

logger = getLogger(os.environ.get('APP_NAME'))

@app.get('/api')
async def api() -> dict:
    """测试接口"""
    return {'title': 'FastApp'}

@app.get('/api_test')
async def api_test(name: str) -> dict:
    """测试异常接口"""
    try:
        print(username)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

    return {'title': 'FastApp'}


@app.get('/sms/{mobile}')
async def sms(request: Request, mobile: str) -> dict:
    """
    发送验证码
    @param request: 本次HTTP请求对象
    @param mobile: 要接收验证码的手机
    return
    """
    # 获取redis操作对象
    redis = request.app.state.redis
    # 生成随机验证码
    code = func.gen_int(5)
    # 把验证码保存到redis并设置有效期
    ret = await redis.setex(f"sms_{mobile}", int(settings.ALIYUN['sms']['expire_time']), code)
    if ret:
        # 发送短信
        aliyun = aliyunclound.AliYunClound(settings.ALIYUN['key'], settings.ALIYUN['secret'])
        data = {
            'code': code
        }
        result = await aliyun.sms_async(mobile, data, settings.ALIYUN['sms']['sign_name'], settings.ALIYUN['sms']['template_code'])

        if result.code != 'OK':
            logger.error(f'短信发送失败！{result.message}')
            raise HTTPException(status_code=500, detail='短信发送失败！')
        return {
            'code': 200,
            'err_msg': '短信已发送，请留意手机',
            'status': 'Success',
        }
